const express= require('express');
const common = require('../../../libs/common');
const reg = require('../../../libs/reg');
const request = require('request');

let router = express.Router();
module.exports = router;

router.post('/',(req,res)=>{
    let {cardNo,password,periodTime,payMode} = req.body;
    // 做效验
    if(!reg.cardNumReg.test(cardNo)){
        let regData={
            status:2,
            msg:"Wrong card number information"
        }
        res.send(regData)
    }else if(!reg.cardPwdReg.test(password)){
        let regData={
            status:2,
            msg:"Wrong card number information"
        }
        res.send(regData)
    }else if(!reg.cardTimeReg.test(periodTime)){
        let regData={
            status:2,
            msg:"Wrong card number information"
        }
        res.send(regData)
    }else{
        // 判断邮箱验证码是否正确
        req.db.query(`SELECT ID FROM user WHERE ID='${req.session['car_user_ID']}'`, (err, data) => {
            if (err) {
                res.sendStatus(500);
            } else if(data ==0){
                let regData={
                    status:2, 
                    msg:"Please login again"
                }
                res.send(regData)
            } else {
                let userId = data[0].ID
                // 生成UUID
                function createID(fn) {
                    let id = common.uuid();
                    req.db.query(`SELECT ID FROM pay_order WHERE ID='${id}'`, (err, data) => {
                        if (err) {
                            res.sendStatus(500);
                        } else if (data.length > 0) {
                            createID();
                        } else {
                            fn(id);
                        }
                    })
                }
                createID(function(id){
                    let appId = "10139";
                    let appSecret = "96c94ebc7686b19bfdb59150737a1947";
                    let orderId = id;
                    let feeType = 'RMB';
                    let feeTotal = common.returnFloat(detailData[row]['price']);
                    let token = '123';
                    let nonce=common.randomString(4);   //4位随机字符串
                    let timestamp=String(Date.parse(new Date()) / 1000);  // 当前时间
                    let IP = "124.89.116.4";
                    let arr = [ orderId,  feeType, feeTotal, token,nonce,timestamp,IP];
                    arr.sort()
                    let str = '';
                    for (let i = 0; i < arr.length; i++) {
                        str += arr[i];
                    }
                    let signature = common.sha1(str);
                    let params={}
                    params['appId']=appId;
                    params['appSecret']=appSecret;
                    params['cardSn']=cardNo;
                    params['cardPwd']=password;
                    params['expirationTime']=periodTime;
                    params['orderId']=orderId;
                    params['feeType']=feeType;
                    params['feeTotal']=feeTotal;
                    params['signature']=signature;
                    params['timestamp']=timestamp;
                    params['nonce']=nonce;
                    params['ip']=IP;
                    request.post({
                        url: 'http://api.yinglouxia.com/v1/pay', form: params
                    }, function (err, httpResponse, body) {
                        console.log(`INSERT INTO pay_order (ID,user_id,price,payment_time,payment_mode,product_name) VALUES ('${orderId}','${userId}','${feeTotal}','${timestamp}',${Number(payMode)},'${detailData[row]['title']}')`)
                        if((JSON.parse(body)).code==1){
                            req.db.query(`INSERT INTO pay_order (ID,user_id,price,payment_time,payment_mode,product_name) VALUES ('${orderId}','${userId}','${feeTotal}','${timestamp}',${Number(payMode)},'${detailData[row]['title']}')`,(err,data)=>{
                                if(err){
                                    res.sendStatus(500);
                                }else{
                                    res.send(body) 
                                }
                            })
                        }else{
                            res.send(body) 
                        }   
                    }) 
                })
            }
        })
        
    }
})
